package com.guangfeng.yql.comm.netty.handler;

import com.guangfeng.yql.comm.netty.message.NettyMessage;
import com.guangfeng.yql.comm.netty.message.NettyMessageResolveFactory;
import com.guangfeng.yql.comm.netty.util.ChatRoomUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

@ChannelHandler.Sharable
@Component
public class ChatRoomHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 监听客户端注册
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        // 加入到队列中
        ChatRoomUtil.append(ctx.channel());
    }

    /**
     * 监听客户端断开
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        ChatRoomUtil.delete(ctx);
    }

    /**
     * 监听连接异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ChatRoomUtil.delete(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) {
        NettyMessage message = NettyMessageResolveFactory.getNettyMessage(textWebSocketFrame);
        message.tactics(channelHandlerContext, textWebSocketFrame);
    }
}
